﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Activities;
using System.ComponentModel;
using System.Text.RegularExpressions;

namespace TfsExtensions.Build.Activities
{

    public sealed class ExtractBuildNumber : CodeActivity
    {
        public OutArgument<string> BuildDate { get; set; }
        public OutArgument<string> RevisionNumber { get; set; }
        public OutArgument<string> BuildName { get; set; }
        
        [Description(@"Build number should be of the format $(BuildDefinitionName)_$(Date:yyyyMMdd)$(Rev:.r)")]
        [RequiredArgument]
        public InArgument<string> BuildNumber { get; set; }


        // If your activity returns a value, derive from CodeActivity<TResult>
        // and return the value from the Execute method.
        protected override void Execute(CodeActivityContext context)
        {
            // $(BuildDefinitionName)_$(Date:yyyyMMdd)$(Rev:.r)
            string regExPattern = @"(?<BuildDate>[0-9]{8})\.(?<BuildNumber>[0-9]*)";

            var regex = new Regex(regExPattern);

            var buildNumber = this.BuildNumber.Get(context);
            Match match = regex.Match(buildNumber);

            this.BuildDate.Set(context, match.Groups["BuildDate"].Value);
            this.RevisionNumber.Set(context,match.Groups["BuildNumber"].Value);

            int underscorePosition = buildNumber.LastIndexOf('_');

            if (underscorePosition > 0)
            {
                this.BuildName.Set(context, buildNumber.Substring(0, underscorePosition));
            }

        }
    }
}


